package com.b2.service.impl;

import com.b2.constant.MessageConstant;
import com.b2.constant.StatusConstant;
import com.b2.context.BaseContext;
import com.b2.mapper.DirectorMapper;
import com.b2.mapper.DirectorVideoMapper;
import com.b2.mapper.UserMapper;
import com.b2.mapper.VideoMapper;
import com.b2.pojo.dto.*;
import com.b2.pojo.entity.Director;
import com.b2.pojo.entity.DirectorVideo;
import com.b2.pojo.entity.User;
import com.b2.pojo.entity.Video;
import com.b2.pojo.vo.DirectorVideoInformation;
import com.b2.pojo.vo.adminGetworksVo;
import com.b2.properties.AiProperties;
import com.b2.properties.WeChatProperties;
import com.b2.service.AdminService;
import com.b2.service.DirectorVideoService;
import com.b2.service.PushService;
import com.b2.utils.AliOssUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author 悦神
* @description 针对表【director_video】的数据库操作Service实现
* @createDate 2024-05-23 14:34:41
*/
@Service
public class DirectorVideoServiceImpl extends ServiceImpl<DirectorVideoMapper, DirectorVideo>
    implements DirectorVideoService{
   @Autowired
    AiProperties aiProperties;
    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    DirectorVideoMapper directorVideoMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    DirectorMapper directorMapper;
    @Autowired
    VideoMapper videoMapper;
    @Autowired
    private PushService pushService;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private AdminService adminService;

    @Override
    public void directorcommitvideo(DirectorCommitVideoDto directorCommitVideoDto) {
        //通过用户id关联得出directorid
        Long currentId = BaseContext.getCurrentId();
        User user = userMapper.selectById(currentId);
        String phone = user.getPhone();
        LambdaQueryWrapper<Director> o1 = new LambdaQueryWrapper<>();
        o1.eq(Director::getPhone,phone);
        Director director = directorMapper.selectOne(o1);
        Long id = director.getId();
        DirectorVideo directorVideo = new DirectorVideo();
        directorVideo.setDirectorId(id);
        directorVideo.setDirectorVideoUrl(directorCommitVideoDto.getParentVideoUrl());
        directorVideo.setVideoId(directorCommitVideoDto.getVideoId());
        directorVideo.setCreateTime(LocalDateTime.now());
        directorVideo.setStatus(StatusConstant.BEFORE_CORRECTION);
        directorVideoMapper.insert(directorVideo);
//        //消息通知
//        try {
//            //教师成功上传通知给园长
//            String accessToken = pushService.refreshAccessToken(weChatProperties.getAppid(),weChatProperties.getSecret());
//            //获取管理者的openId
//            String s = adminService.getById(2).getPhone();
//            String openid = userMapper.selectOne(Wrappers.<User>lambdaQuery()
//                    .eq(StringUtils.isNotBlank(s), User::getPhone, s)).getOpenid();
//            String templateId = weChatProperties.getTemplateId();
//            String page = "http://picture.mark.syssts.com:9090/classVideo";
//            // 构建订阅消息内容的JSON对象
//            // 构建订阅消息内容的JSON对象
//            JSONObject messageData = new JSONObject();
//            messageData.put("thing4", pushService.createDataItem("课程名称", videoMapper.selectById(directorCommitVideoDto.getVideoId()).getVideoName()));
//            messageData.put("thing5", pushService.createDataItem("教师", director.getName()));
//            messageData.put("thing6", pushService.createDataItem("备注", "您提交的视频已经上线了，欢迎查看！"));
//            messageData.put("time7", pushService.createDataItem("时间", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
//            // 将订阅消息内容转换为JSON字符串
//            String jsonData = messageData.toJSONString();
//            pushService.sendSubscribeMessage(accessToken,openid,templateId,page,jsonData);
//        } catch (Exception e) {
//            log.error("发送订阅消息失败:{}", e);
//        }
    }

    @Override
    public DirectorVideoInformation getinformation(Long videoid) {
        Long currentId = BaseContext.getCurrentId();
        User user = userMapper.selectById(currentId);
        String phone = user.getPhone();
        LambdaQueryWrapper<Director> o1 = new LambdaQueryWrapper<>();
        o1.eq(Director::getPhone,phone);
        Director director = directorMapper.selectOne(o1);
        Long id = director.getId();
        //通过classid得到teacherid
        //Class aClass = classMapper.selectById(classid);
        //Long teacherId = aClass.getTeacherId();

        LambdaQueryWrapper<DirectorVideo> o2 = new LambdaQueryWrapper<>();
        o2.eq(DirectorVideo::getDirectorId,id);
        o2.eq(DirectorVideo::getVideoId,videoid);
        DirectorVideo directorVideo = directorVideoMapper.selectOne(o2);

        if (directorVideo==null)
        {
            return null;
        }
        DirectorVideoInformation directorVideoInformation = new DirectorVideoInformation();
        directorVideoInformation.setDirectorVideoUrl(directorVideo.getDirectorVideoUrl());
        directorVideoInformation.setId(directorVideo.getId());
        directorVideoInformation.setStatus(directorVideo.getStatus());
        directorVideoInformation.setAdminResponse(directorVideo.getAdminResponse());
        directorVideoInformation.setCreateTime(directorVideo.getCreateTime());
        directorVideoInformation.setOverrule(directorVideo.getOverrule());
        directorVideoInformation.setAiResponse(directorVideo.getAiResponse());
        return directorVideoInformation;
    }

    @Override
    public Integer getstatus(Long id) {
        DirectorVideo directorVideo = directorVideoMapper.selectById(id);
        if(directorVideo.getStatus()==1){
            directorVideo.setStatus(100);
            directorVideoMapper.updateById(directorVideo);
        }
        return directorVideo.getStatus();
    }

    @Override
    public void directorupdatevideo(DirectorUpdateVideoDto directorUpdateVideoDto) {
        //批改后用户不能在修改
        DirectorVideo directorVideo1 = directorVideoMapper.selectById(directorUpdateVideoDto.getId());
        if (directorVideo1.getStatus()==1) {
            throw new RuntimeException(MessageConstant.UPDATE_FAIL);
        }

        DirectorVideo directorVideo = new DirectorVideo();

        directorVideo.setId(directorUpdateVideoDto.getId());

        directorVideo.setDirectorVideoUrl(directorUpdateVideoDto.getNewDirectorVideoUrl());
        //修改后将状态设置为未批改
        directorVideo.setStatus(StatusConstant.BEFORE_CORRECTION);

        directorVideoMapper.updateById(directorVideo);

        aliOssUtil.deleteFile(directorUpdateVideoDto.getOldDirectorVideoUrl());
    }

    @Override
    public List<adminGetworksVo> admingetworks(adminGetWorksDto adminGetWorksDto) {
        LambdaQueryWrapper<DirectorVideo> o = new LambdaQueryWrapper<>();
        o.eq(adminGetWorksDto.getStatus()!=null,DirectorVideo::getStatus,adminGetWorksDto.getStatus());

        List<DirectorVideo> directorVideos = directorVideoMapper.selectList(o);

        List<adminGetworksVo> adminGetworksVos = new ArrayList<>();
        for (DirectorVideo d:directorVideos) {
            Long directorId = d.getDirectorId();
            Director director = directorMapper.selectById(directorId);

            Video video = videoMapper.selectById(d.getVideoId());
            if (video==null) {
                continue;
            }

            adminGetworksVo adminGetworksVo = new adminGetworksVo();
            adminGetworksVo.setId(d.getId());
            adminGetworksVo.setDirectorVideoUrl(d.getDirectorVideoUrl());
            adminGetworksVo.setAdminResponse(d.getAdminResponse());
            adminGetworksVo.setCreateTime(d.getCreateTime());
            adminGetworksVo.setDirectorname(director.getName());
            adminGetworksVo.setVideoname(video.getVideoName());
            adminGetworksVo.setStatus(d.getStatus());
            adminGetworksVo.setOverrule(d.getOverrule());
            adminGetworksVos.add(adminGetworksVo);
        }
        return adminGetworksVos;
    }

    @Override
    public String getAiresponse(AiDto aiDto) {

        DirectorVideo directorVideo = new DirectorVideo();
        String post;
        try {
            post = this.post(aiProperties.getAiUrl(), aiDto.getImageUrl());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        directorVideo.setId(aiDto.getId());
        directorVideo.setAdminPictureUrl(aiDto.getImageUrl());
        directorVideo.setAiResponse(post.toString());
        directorVideoMapper.updateById(directorVideo);
        return post.toString();
    }

    @Override
    public void putadminResponse(adminResponseDto dto) {

       //驳回状态不可批改
        DirectorVideo directorVideo1 = directorVideoMapper.selectById(dto.getId());
        if (directorVideo1.getStatus()==2) {
            throw new RuntimeException(MessageConstant.RESPONSE_FAIL);
        }


        DirectorVideo directorVideo = new DirectorVideo();
        directorVideo.setId(dto.getId());
        directorVideo.setAdminResponse(dto.getResponse());
        //评论后将工作设置为已完成
        directorVideo.setStatus(StatusConstant.AFTER_CORRECTION);
        directorVideoMapper.updateById(directorVideo);
    }

    @Override
    public void adminUpdateStatus(Long id,String overrule) {
        DirectorVideo directorVideo = new DirectorVideo();
        DirectorVideo directorVideo1 = directorVideoMapper.selectById(id);
         //批改后不能驳回
        if (directorVideo1.getStatus()==1) {
            throw new RuntimeException(MessageConstant.STATUS_FAIL);
        }
        directorVideo.setId(id);
        directorVideo.setStatus(StatusConstant.FAIL);
        directorVideo.setOverrule(overrule);
        directorVideoMapper.updateById(directorVideo);
    }

    private String post(String postURL,String name) throws Exception {
        PostMethod postMethod = new PostMethod(postURL);
        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        //参数设置，需要注意的就是里边不能传NULL，要传空字符串
        NameValuePair[] data = {
                new NameValuePair("image", name)
        };
        postMethod.setRequestBody(data);
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        httpClient.executeMethod(postMethod);
        String result = postMethod.getResponseBodyAsString();
        System.out.println(result.toString());
        return result;

    }
}




